<script lang="ts" setup>
import { ref, computed } from 'vue'
import Department from '@/api/department'

const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  currentNodeId: {
    type: Number,
    default: null
  }
})

const formRef = ref()
const formData = ref({
  code: '', // 部门编码
  introduce: '', // 部门介绍
  managerId: '', // 部门负责人id
  name: '', // 部门名称
  pid: '' // 父级部门的id
} as any)
const showTitle = computed(() => {
  return formData.value.id ? '编辑部门' : '新增部门'
})

const dialogRules = {
  code: [
    { required: true, message: '部门编码不能为空', trigger: 'blur' },
    {
      min: 2,
      max: 10,
      message: '部门编码的长度为2-10个字符',
      trigger: 'blur'
    },
    {
      validator: async (rule: any, value: any, callback: any) => {
        // value就是输入的编码
        let res: any = await Department.getDepartmentService()
        // 判断是否是编辑模式
        if (formData.value.id) {
          // 编辑场景，排除自身
          res = res.filter((item: any) => item.id !== formData.value.id)
        }
        if (res.some((item: any) => item.code === value)) {
          // res数组中是否存在value值，some()遍历数组中的每一项，如果有任意一项满足指定条件，则返回 true
          callback(new Error('部门编码已存在'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ], // 部门编码
  introduce: [
    { required: true, message: '部门介绍不能为空', trigger: 'blur' },
    {
      min: 1,
      max: 100,
      message: '部门介绍的长度为1-100个字符',
      trigger: 'blur'
    }
  ], // 部门介绍
  managerId: [
    { required: true, message: '部门负责人不能为空', trigger: 'blur' }
  ], // 部门负责人id
  name: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' },
    {
      min: 2,
      max: 10,
      message: '部门名称的长度为2-10个字符',
      trigger: 'blur'
    },
    ,
    {
      validator: async (rule: any, value: any, callback: any) => {
        // value就是输入的编码
        let res: any = await Department.getDepartmentService()
        // 判断是否是编辑模式
        if (formData.value.id) {
          // 编辑场景，排除自身
          res = res.filter((item: any) => item.id !== formData.value.id)
        }
        // res数组中是否存在value值，some()遍历数组中的每一项，如果有任意一项满足指定条件，则返回 true
        if (res.some((item: any) => item.name === value)) {
          callback(new Error('部门名称已存在'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ] // 部门名称
} as any

const managerList = ref([] as any) // 部门负责人列表
async function GetManagerList() {
  managerList.value = await Department.getManagerListService()
}
GetManagerList()

// 确定
const emit = defineEmits(['update:showDialog', 'updateDep'])
const confirm = async () => {
  await formRef.value.validate()
  // 表单校验通过后
  let msg = '新增'
  if (formData.value.id) {
    // 编辑场景
    msg = '更新'
    await Department.updateDepartmentService(formData.value)
  } else {
    // 新增场景
    await Department.addDepartmentService({
      ...formData,
      pid: props.currentNodeId
    })
  }

  // 通知父组件更新，执行getDepartment()
  emit('updateDep')
  ElMessage.success(`${msg}部门成功`)
}

// 关闭弹窗后重置表单
const closedFun = () => {
  emit('update:showDialog', false)
  formRef.value.resetFields()
  // resetFields只能重置在模版中绑定的数据
  // 手动重置
  formData.value = {
    code: '',
    introduce: '',
    managerId: '',
    name: '',
    pid: ''
  }
}

const getDepartmentDetail = async () => {
  formData.value = await Department.getDepartmentDetailService(
    props.currentNodeId
  )
}

defineExpose({ getDepartmentDetail })
</script>

<template>
  <el-dialog :title="showTitle" :closed="closedFun">
    <!-- 放置弹层内容 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="dialogRules"
      lable-width="120px"
    >
      <el-form-item prop="name" lable="部门名称">
        <el-input
          v-model="formData.name"
          placeholder="2-10个字符"
          style="width: 80%"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item prop="code" lable="部门编码">
        <el-input
          v-model="formData.code"
          placeholder="2-10个字符"
          style="width: 80%"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item prop="managerId" lable="部门负责人">
        <el-select
          v-model="formData.managerId"
          placeholder="请选择负责人"
          style="width: 80%"
          size="small"
        >
          <!-- 下拉选项 -->
          <el-option
            v-for="item in managerList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" lable="部门介绍">
        <el-input
          v-model="formData.introduce"
          placeholder="1-100个字符"
          type="textarea"
          :row="4"
          style="width: 80%"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 按钮 -->
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button @click="confirm" size="small" type="primary"
              >确定</el-button
            >
            <el-button @click="closedFun" size="small">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
